package com.nuaa.ange.rabbitmq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nuaa.ange.config.RabbitMqConfig;
import com.nuaa.ange.service.ElasticSearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @description 监听异步消息队列 更新搜索内容
 * @author 玦离
 * @date 2023/1/2 14:06
 */

@Slf4j
@Component
@RabbitListener(queues = RabbitMqConfig.ES_QUEUE)
@RequiredArgsConstructor
public class HandlerMessage {

    private ObjectMapper objectMapper;

    ElasticSearchService elasticSearchService;

    @RabbitHandler
    public void handler(String content) {
        PostMqIndexMessage message = null;
        try {
            message = objectMapper.readValue(content, PostMqIndexMessage.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        switch (message.getType()) {
            case PostMqIndexMessage.CREATE:
                elasticSearchService.createDoc(message.getArticle());
                break;
            case PostMqIndexMessage.UPDATE:
                elasticSearchService.updateDoc(message.getArticle());
                break;
            case PostMqIndexMessage.REMOVE:
                elasticSearchService.deleteDoc(message.getPostId());
                break;
            default:
                log.warn("没有找到对应的消息类型，请注意！！！, --->  {}", content);
                break;
        }
    }
}

